package com.jp.knowledge.my.fragment;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.jp.knowledge.R;
import com.jp.knowledge.my.model.OrganizaModel;
import com.jp.knowledge.util.QRCodeUtils;
import com.jp.knowledge.util.ShareBuilder;
import com.jp.knowledge.view.SquareImageView;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.media.UMImage;

/**
 * Created by 528787067@qq.com on 2017/7/4.
 */

public class InvitePeopleFragment extends Fragment {

	private Context mContext;
	private String userName;
	private OrganizaModel organizaModel;
	private SquareImageView qrCodeImg;
	private TextView shareBtn;
	private View contentView;
	private ShareAction shareAction;

	public InvitePeopleFragment getInstance(String username, OrganizaModel organizaModel){
		this.userName = username;
		this.organizaModel = organizaModel;
		return this;
	}

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		if(contentView == null){
			mContext = getContext();
			contentView = View.inflate(mContext, R.layout.fragment_invite_people, null);
			qrCodeImg = (SquareImageView) contentView.findViewById(R.id.invite_qr_code);
			shareBtn = (TextView) contentView.findViewById(R.id.invite_share);
			initShare();
			shareBtn.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					shareAction.open();
				}
			});
			showQrCode(organizaModel.getInviteUrl());
		}
		return contentView;
	}

	private void initShare(){
		String shareText = userName + "邀请你加入"
				+ organizaModel.getCompanyFullName() + "。马上点击链接"
				+ organizaModel.getInviteUrl() + "加入吧！";
		shareAction =  new ShareBuilder(getActivity())
				.withTitle(mContext.getResources().getString(R.string.app_name))
				.withText(shareText)
				.withMedia(new UMImage(mContext, R.mipmap.icon_launcher))
				.withTargetUrl(organizaModel.getInviteUrl())
				.withCopyContent(organizaModel.getInviteUrl())
				.withQRCodeUrl(organizaModel.getInviteUrl())
				.build();
	}

	private void showQrCode(String url){
		QRCodeUtils.encodeAsBitmap(url, new QRCodeUtils.EncodeListener() {
			@Override
			public void encodeSuccedd(Bitmap qrCode) {
				qrCodeImg.setImageBitmap(qrCode);
			}
			@Override
			public void encodeError(Throwable e) {
				qrCodeImg.setImageResource(R.mipmap.morentutouxiang);
			}
		});
	}
}
